package com.eptok.gw.szcups.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DES {
	private final static String	DES	= "DES";

	/** 
	 * 加密 
	 * @param src 数据源 
	 * @param key 密钥，长度必须是8的倍数 
	 * @return 返回加密后的数据 
	 * @throws Exception 
	 */
	public static byte[] encrypt(final byte[] src, final byte[] key) throws Exception {
		//	DES算法要求有一个可信任的随机数源 
		final SecureRandom sr = new SecureRandom();
		//	 从原始密匙数据创建DESKeySpec对象 
		final DESKeySpec dks = new DESKeySpec(key);
		//	 创建一个密匙工厂，然后用它把DESKeySpec转换成 
		//	 一个SecretKey对象 
		final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		final SecretKey securekey = keyFactory.generateSecret(dks);
		//	 Cipher对象实际完成加密操作 
		final Cipher cipher = Cipher.getInstance(DES);
		//	 用密匙初始化Cipher对象 
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
		//	 现在，获取数据并加密 
		//	 正式执行加密操作 
		return cipher.doFinal(src);
	}

	public static void main(final String[] args) throws Exception {

		// String key = "1234567890ABCDEF";
		final String src = "123456789012345678      ";
		final String res = "A103655BB883050CA9BF5F83AD5D71924CC8A475BC6381B0 ";

		final byte[] bk = new byte[8];
		bk[0] = Integer.decode("0x12").byteValue();
		bk[1] = Integer.decode("0x34").byteValue();
		bk[2] = Integer.decode("0x56").byteValue();
		bk[3] = Integer.decode("0x78").byteValue();
		bk[4] = Integer.decode("0x90").byteValue();
		bk[5] = Integer.decode("0xAB").byteValue();
		bk[6] = Integer.decode("0xCD").byteValue();
		bk[7] = Integer.decode("0xEF").byteValue();

		final byte[] bs = src.getBytes();

		final byte[] br = encrypt(bs, bk);

		System.out.println(res);

		for (int i = 0; i < br.length; i++) {
			System.out.print(Integer.toHexString(br[i]));
			System.out.print(",");
		}

		System.out.print("\r\n");

		for (int i = 0; i < br.length; i++) {
			System.out.print(dec2hex(br[i]));

		}

	}

	public static String dec2hex(final int i) {
		String hex;
		if (i >= 0) {
			hex = Integer.toHexString(i);
		} else {
			hex = Integer.toHexString(256 + i);
		}
		if (hex.length() == 1) {
			hex = "0" + hex;
		}
		return hex.toUpperCase();
	}

}
